  <!-- src/layout/index.vue -->
  <template>
    <div class="common-layout">
      <el-container>
        <el-aside :width="isMenuCollapsed ? '64px' : '200px'">
          <mymenu :conf="conf" @collapse="handleMenuCollapse" />
        </el-aside>

        <el-container class="main-container" :style="{ 'margin-left': isMenuCollapsed ? '64px' : '200px' }">
          <el-header class="header">
            <div class="header-usercenter" @click="userClick">
              <img class="user-avatar" :src="userImg || defaultAvatar" alt="avatar" />
              <div class="phone">{{ userphone }}</div>
            </div>
            <div @click="exit" style="cursor: pointer">退出</div>
          </el-header>

          <mbx />

          <el-main class="content-area">
            <RouterView />
          </el-main>
        </el-container>
      </el-container>

      <!-- 个人中心 -->
      <el-dialog v-model="dialogVisible" title="个人中心" width="500">
        <el-form ref="formRef" style="max-width: 600px" :model="form" label-width="auto" label-position="top">

          <!-- 头像 -->
          <el-form-item label="头像">
            <div style="display:flex;align-items:center;">
              <img :src="userImg || defaultAvatar"
                style="width:80px;height:80px;border-radius:50%;object-fit:cover;margin-right:12px" />
              <el-upload class="avatar-uploader" :show-file-list="false" :before-upload="beforeAvatarUpload"
                :http-request="uploadAvatar"> <!-- 只保留 http-request -->
                <el-button type="primary" :loading="uploading">更换头像</el-button>
              </el-upload>
            </div>
          </el-form-item>

          <el-form-item label="用户ID">
            <el-input v-model="form.userId" disabled />
          </el-form-item>

          <el-form-item label="用户名">
            <el-input v-model="form.name" />
          </el-form-item>

          <!-- 手机号 -->
          <el-form-item label="手机号" prop="phone">
            <div style="display: flex; width: 100%">
              <el-input v-model="form.phone" :readonly="!smsVerified" />
              <el-button style="margin-left: 8px" :disabled="smsCoolDown > 0" @click="handleSendSms">
                {{ smsCoolDown > 0 ? `${smsCoolDown}s` : "获取验证码" }}
              </el-button>
            </div>
          </el-form-item>

          <!-- 验证码 -->
          <el-form-item label="短信验证码">
            <div style="display: flex; width: 100%">
              <el-input v-model="form.smsCode" placeholder="请输入验证码" />
              <el-button style="margin-left: 8px" :disabled="!form.smsCode" @click="handleVerifySms">
                验证
              </el-button>
            </div>
          </el-form-item>

          <el-form-item label="微信绑定">
            <el-input v-model="form.wechat" />
          </el-form-item>

          <el-form-item label="账号权限">
            <el-select v-model="form.role" placeholder="请选择" :readonly="true">
              <el-option label="超级管理员" value="1" />
              <el-option label="财务" value="2" />
            </el-select>
          </el-form-item>

          <el-form-item label="账号状态">
            <el-select v-model="form.status" placeholder="请选择">
              <el-option label="正常" value="1" />
              <el-option label="冻结" value="2" />
            </el-select>
          </el-form-item>
        </el-form>

        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" :loading="saveLoading" @click="handleSave">
              确认
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </template>

<script lang="ts" setup>
import mymenu from "@/components/mymenu.vue";
import mbx from "@/components/mbx.vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { ref, reactive, onMounted, watch, computed } from "vue";
import { userLogout, getInfo, getsendSms, upload } from "@/api/login";
import { userAdd } from "@/api/userOr";
import { baseURL, apiClient } from '@/utils/request'
import defaultAvatarUrl from '../assets/logo.png';

const defaultAvatar = defaultAvatarUrl;  // 默认图
const uploading = ref(false);               // 上传 loading
const uploadRef = ref();
const aburl = baseURL + '/user/upload'
const dialogVisible = ref(false);
const userImg = ref("");
const userphone = ref("");
const router = useRouter();
const isMenuCollapsed = ref(false);
const userId = localStorage.getItem("userId");
const smsCoolDown = ref(0);
let smsTimer: any = null;
const saveLoading = ref(false);
const smsVerified = ref(false); // 是否已通过短信验证
const fullAvatar = (path: string) =>
  path && !path.startsWith('http') ? baseURL + path : path;
const form = reactive({
  userId: "",
  name: "",
  phone: "",
  avatar: "",
  smsCode: "",
  wechat: "",
  role: "",
  status: "",
});

/* ---------- 菜单配置 ---------- */
const conf = [
  { title: "首页", path: "/Dashboard", imageUrl: "/assets/11.png", activeImageUrl: "/assets/12.png", isCollapsed: false },
  {
    title: "直播管理", path: "/lives", imageUrl: "/assets/31.png", activeImageUrl: "/assets/32.png", isCollapsed: false,
    children: [{ title: "直播中控台", path: "/live" },
    { title: "直播计划", path: "/plan" }]
  },
  { title: "流量中心", path: "/internet", imageUrl: "/assets/41.png", activeImageUrl: "/assets/42.png", isCollapsed: false},
  { title: "个人中心", path: "/personCenter", imageUrl: "/assets/71.png", activeImageUrl: "/assets/72.png", isCollapsed: false },
  
  // { title: "用户中心", path: "/partys", imageUrl: "/assets/61.png", activeImageUrl: "/assets/62.png", isCollapsed: false, children: [{ title: "企业管理", path: "/anchor" }, { title: "用户管理", path: "/party" }] },
  // { title: "投诉管理", path: "/complaint", imageUrl: "/assets/71.png", activeImageUrl: "/assets/72.png", isCollapsed: false },
  // { title: "日志管理", path: "/daily", imageUrl: "/assets/71.png", activeImageUrl: "/assets/72.png", isCollapsed: false },
  // { title: "设置", path: "/setups", imageUrl: "/assets/81.png", activeImageUrl: "/assets/82.png", isCollapsed: false, children: [{ title: "账号管理", path: "/setup" }] },
];

const handleMenuCollapse = (collapsed: boolean) => {
  isMenuCollapsed.value = collapsed;
};

/*  退出登录  */
const exit = async () => {
  try {
    await ElMessageBox.confirm("确定要退出登录吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });
    const params = { token: localStorage.getItem("token") };
    const res = await userLogout(params);
    if (res.code === 200) {
      localStorage.removeItem("token");
      ElMessage.success("已退出登录");
      router.push("/login");
    }
  } catch {
    ElMessage.info("已取消退出");
  }
};

/*  短信相关  */
const handleSendSms = async () => {
  if (!form.phone) {
    ElMessage.warning("请先填写手机号");
    return;
  }
  try {
    await getsendSms(form.phone);
    ElMessage.success("验证码已发送");
    smsCoolDown.value = 60;
    smsVerified.value = false;
    smsTimer = setInterval(() => {
      smsCoolDown.value--;
      if (smsCoolDown.value <= 0) clearInterval(smsTimer);
    }, 1000);
  } catch {
    ElMessage.error("发送失败，请重试");
  }
};

const handleVerifySms = async () => {
  if (!form.smsCode.trim()) {
    ElMessage.warning("请输入验证码");
    return;
  }
  try {
    if (form.smsCode === "data.smsCode")
      ElMessage.success("验证码正确");
    smsVerified.value = true;
  } catch {
    ElMessage.error("验证码错误");
    smsVerified.value = false;
  }
};

/*  保存  */
const handleSave = async () => {
  // 手机号被修改，但未验证
  if (form.phone !== userphone.value && !smsVerified.value) {
    ElMessage.warning("请先通过短信验证");
    return;
  }
  saveLoading.value = true;
  try {
    const payload = {
      id: form.userId,
      userName: form.name,
      userTel: form.phone,
      smsCode: form.smsCode.trim(),
      userPicture: form.avatar,
    };
    await userAdd(payload);
    ElMessage.success("保存成功");

    // 重新拉取信息
    const { data } = await getInfo(form.userId);
    form.name = data.userName;
    form.phone = data.userTel;
    form.role = String(data.userRole);
    form.status = data.isBanned ? "2" : "1";
    userphone.value = data.userTel;
    localStorage.setItem('userPicture', data.userPicture);
    localStorage.setItem("userTel", data.userTel);
    form.smsCode = "";
    dialogVisible.value = false;
  } catch (e: any) {
    ElMessage.error(e?.msg || "保存失败");
  } finally {
    saveLoading.value = false;
  }
};

/* 打开弹窗*/
const userClick = async () => {
  try {
    const { data } = await getInfo(userId);
    form.avatar = data.userPicture;
    localStorage.setItem("userPicture", data.userPicture);
    form.userId = String(data.id);
    form.name = data.userName;
    form.phone = data.userTel;
    form.role = String(data.userRole || '1');
    form.status = data.isBanned ? "2" : "1";
    form.wechat = "";
    userImg.value = data.userPicture;
    userphone.value = data.userTel;
    smsVerified.value = false; // 重置
    dialogVisible.value = true;
  } catch {
    ElMessage.error("获取用户信息失败");
  }
};


// 头像
const beforeAvatarUpload = (rawFile: File) => {
  const isImage = rawFile.type.startsWith('image/');
  const isLt2M = rawFile.size / 1024 / 1024 < 2;
  if (!isImage) {
    ElMessage.error('请上传图片格式文件');
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB');
  }
  return isImage && isLt2M;
};

// 真正执行上传
// 上传接口
const uploadAvatar = async ({ file }: { file: File }) => {
  uploading.value = true;
  try {
    // 1. 用 FormData（后端支持 multipart/form-data 最通用）
    const fd = new FormData();
    fd.append('file', file);   // 字段名必须与后端一致（这里是 file）
    // 2. 直接调用 apiClient，手动把 Content-Type 设为 multipart
    const res = await apiClient.post('/user/upload', fd, {
      headers: { 'Content-Type': 'multipart/form-data' }
    });
    if (res.code === 200) {
      form.avatar = res.data;
      localStorage.setItem('userPicture', res.data);
      userImg.value = res.data;
      ElMessage.success('头像上传成功');
    } else {
      ElMessage.error('上传失败');
    }
  } catch (e: any) {
    console.error(e);
    ElMessage.error('网络异常，上传失败');
  } finally {
    uploading.value = false;
  }
};
/* ---------- 生命周期 ---------- */
onMounted(async () => {
  try {
    const { data } = await getInfo();
    userImg.value = data.userPicture || defaultAvatar;
    userphone.value = data.userTel || "";
    localStorage.setItem("userPicture", data.userPicture);
    localStorage.setItem("userTel", data.userTel);
  } catch {
    userImg.value = localStorage.getItem("userPicture") || defaultAvatar;
    userphone.value = localStorage.getItem("userTel") || "";
  }
});

watch(dialogVisible, (v) => {
  if (!v) smsVerified.value = false;
});
</script>
<style scoped>
.el-main {
  --el-main-padding: 0px;
}

.common-layout {
  min-height: 100vh;
}

.el-aside {
  position: fixed;
  height: 100vh;
  z-index: 100;
  transition: width 0.3s ease;
}

.main-container {
  transition: margin-left 0.3s ease;
  min-height: 100vh;
}

.header {
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  padding: 0 20px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.content-area {
  background-color: #f8f8f8;
  padding: 20px;
  min-height: calc(100vh - 120px);
}

.header-usercenter {
  display: flex;
  border-right: 1px solid #999;
  margin-right: 20px;
  cursor: pointer;

  img {
    width: 24px;
    height: 24px;
    border-radius: 50%;
  }

  .phone {
    margin: 0px 20px 0px 10px;
  }
}
</style>